<template>
  <div class="outbound-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>出库管理</h2>
          <div class="header-actions">
            <el-button type="success" @click="openAiAssistant" :icon="ChatDotRound">
              🌙 AI助手
            </el-button>
            <el-button type="primary" @click="addOutbound">新增出库单</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="出库单号">
          <el-input v-model="searchForm.outboundCode" placeholder="请输入出库单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="出库日期">
          <el-date-picker 
            v-model="searchForm.outboundDate" 
            type="daterange" 
            range-separator="至" 
            start-placeholder="开始日期"
            end-placeholder="结束日期" 
            format="YYYY-MM-DD" 
            value-format="YYYY-MM-DD">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column prop="outboundCode" label="出库单号" width="120">
          <template #default="scope">
            <el-button type="text" @click="viewOutboundDetail(scope.row)" class="outbound-code-link">
              {{ scope.row.outboundCode }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="inOutTypeName" label="出库类型" width="120"></el-table-column>
        <el-table-column prop="warehouseName" label="仓库" width="120"></el-table-column>
        <el-table-column prop="outboundDate" label="出库日期" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.outboundDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="consignee" label="收货人" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="120"></el-table-column>
        <el-table-column prop="userName" label="操作员" width="100"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outboundAllNum" label="总数量" width="100"></el-table-column>
        <el-table-column prop="outboundAllMoney" label="总金额" width="120">
          <template #default="scope">
            ¥{{ (scope.row.outboundAllMoney || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="outboundAllGoods" label="货品信息" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createDate" label="创建日期" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize" 
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total" 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { ChatDotRound } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

// 路由
const router = useRouter();

// AI助手功能
const openAiAssistant = () => {
  router.push('/moonshot-demo');
};

// 搜索表单
const searchForm = reactive({
  outboundCode: '',
  outboundDate: []
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);


// 初始化
onMounted(() => {
  loadData();
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
  } catch (e) {
    return dateString;
  }
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (e) {
    return dateString;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '待审核';
    case 2: return '已审核';
    case 3: return '已出库';
    case 4: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return ''; // 草稿
    case 1: return 'warning'; // 待审核
    case 2: return 'success'; // 已审核
    case 3: return 'success'; // 已出库
    case 4: return 'danger'; // 已取消
    default: return '';
  }
};


// 加载表格数据
const loadData = async () => {
  loading.value = true;

  try {
    // 构建查询参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value
    };

    if (searchForm.outboundCode) {
      params.outboundCode = searchForm.outboundCode;
    }


    if (searchForm.outboundDate && searchForm.outboundDate.length === 2) {
      params.startDate = searchForm.outboundDate[0];
      params.endDate = searchForm.outboundDate[1];
    }
    
    // 调用后端API
    const response = await axios.get('/api/Outbound/GetOutbound', { params });
    
    console.log('出库管理API返回数据:', response.data);
    
    if (response.data && response.data.code === 200) {
      // 根据接口返回的数据结构调整 - 支持多种可能的数据结构
      let data = [];
      
      if (response.data.data) {
        // 如果data是对象且包含data属性
        if (response.data.data.data && Array.isArray(response.data.data.data)) {
          data = response.data.data.data;
        }
        // 如果data直接是数组
        else if (Array.isArray(response.data.data)) {
          data = response.data.data;
        }
        // 如果data是对象但不包含data属性，可能直接包含记录
        else if (typeof response.data.data === 'object') {
          data = [response.data.data];
        }
      }
      
      console.log('处理后的数据:', data);
      
      // 处理数据，确保日期格式正确
      tableData.value = data.map(item => {
        // 确保日期格式正确
        if (item.outboundDate) {
          item.outboundDate = formatDate(item.outboundDate);
        }
        if (item.createDate) {
          item.createDate = item.createDate;
        }
        
        return item;
      });

      // 获取总数 - 支持多种可能的总数字段
      total.value = response.data.data?.totalCount || 
                   response.data.data?.total || 
                   response.data.totalCount || 
                   response.data.total || 
                   data.length || 0;
    } else {
      ElMessage.error(response.data?.message || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取出库数据失败:', error);
    
    // 提供更详细的错误信息
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
      ElMessage.error(`获取数据失败: ${error.response.status} ${error.response.statusText}`);
    } else if (error.request) {
      console.error('请求错误:', error.request);
      ElMessage.error('网络连接失败，请检查网络连接');
    } else {
      console.error('其他错误:', error.message);
      ElMessage.error(`获取数据失败: ${error.message}`);
    }
    
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = [];
    } else {
      searchForm[key] = '';
    }
  });
  handleSearch();
};

// 新增出库单
const addOutbound = () => {
  router.push('/OutboundEdit');
};

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size;
  console.log('改变每页显示数量:', size);
  loadData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  console.log('改变当前页:', page);
  loadData();
};

// 查看详情
const viewDetail = (row) => {
  viewOutboundDetail(row);
};

// 查看出库单详情
const viewOutboundDetail = (row) => {
  console.log('查看出库单详情:', row);
  
  // 将完整的出库单信息存储到sessionStorage中，供详情页面使用
  sessionStorage.setItem('currentOutboundInfo', JSON.stringify(row));
  
  // 跳转到出库详情页面，传递出库ID和出库单号
  router.push({
    name: 'OutboundDetail',
    params: { id: row.outboundId || row.id },
    query: { 
      outboundCode: row.outboundCode 
    }
  });
};
</script>

<style scoped>
.outbound-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.outbound-code-link {
  color: #409eff;
  font-weight: bold;
  padding: 0;
}

.outbound-code-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>
